package org.summerframework.component.security.core.resolver.cid;

import org.summerframework.component.security.annotion.CIDRequired;
import org.summerframework.component.security.core.interceptor.CIDInterceptor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.annotation.ValueConstants;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.annotation.AbstractNamedValueMethodArgumentResolver;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;

import javax.servlet.http.HttpServletRequest;


/**
 * cid 更新参数
 * {@link CIDRequired}
 * <p>
 * 当cidName=id名称时, 只注入id
 *
 * @author 石超
 * @version v1.0.0
 */
public class CIDMethodArgumentsResolver extends AbstractNamedValueMethodArgumentResolver implements HandlerMethodArgumentResolver {


    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        if (parameter.hasMethodAnnotation(CIDRequired.class)) {
            CIDRequired cidRequired = parameter.getMethodAnnotation(CIDRequired.class);

            if (Long.class.isAssignableFrom(parameter.getParameterType()) || String.class.isAssignableFrom(parameter.getParameterType())) {
                if (StringUtils.equals(parameter.getParameterName(), cidRequired.id())) {
                    return true;
                } else if (StringUtils.equals(parameter.getParameterName(), cidRequired.cid())) {
                    return true;
                }
            }
        }

        return false;
    }

    @Override
    protected NamedValueInfo createNamedValueInfo(MethodParameter parameter) {
        return new NamedValueInfo("", false, ValueConstants.DEFAULT_NONE);
    }

    @Override
    protected Object resolveName(String name, MethodParameter parameter, NativeWebRequest request) throws Exception {
        HttpServletRequest servletRequest = request.getNativeRequest(HttpServletRequest.class);

        Object arg = null;
        CIDInterceptor.CID cid = CIDInterceptor.getCID();

        CIDRequired cidRequired = parameter.getMethodAnnotation(CIDRequired.class);

        if (StringUtils.equals(cidRequired.cid(), cidRequired.id())) {
            if (StringUtils.equals(cidRequired.id(), name)) {
                arg = cid.getCid();
            }
        } else {
            if (StringUtils.equals(cidRequired.cid(), name)) {
                arg = cid.getCid();
            } else if (StringUtils.equals(cidRequired.id(), name)) {
                arg = cid.getId();
            }
        }

        return arg;
    }
}
